package com.wk.springbootlearn.controller;

import com.wk.springbootlearn.pojo.form.*;
import com.wk.springbootlearn.common.model.Response;
import com.wk.springbootlearn.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;

@Api(value = "用户管理", tags = "人员管理模块")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("创建一个用户")
    @PostMapping("/create")
    public Response createUser(@Valid @RequestBody UserForm userForm, @ApiIgnore @RequestAttribute("userId") String userId) {
        userService.createUser(userForm, new Long(userId));
        return new Response().setOK();
    }

    @ApiOperation("分页查询用户信息列表")
    @PostMapping("/finds")
    public Response findAll(@Valid @RequestBody(required = false) GetUsersForm getUsersForm) {
        return new Response().setData(userService.findAll(getUsersForm));
    }

    @ApiOperation("更新一个用户")
    @PutMapping("/update/{id}")
    public Response updateUser(@PathVariable("id") Long id, @Valid @RequestBody(required = false) UpdateUserForm updateUserForm, @ApiIgnore @RequestAttribute("userId") String userId) {
        if (updateUserForm == null) {
            userService.updateUser(id, new UpdateUserForm(), new Long(userId));
        }else {
            userService.updateUser(id, updateUserForm, new Long(userId));
        }
        return new Response().setOK();
    }

    @ApiOperation("修改用户密码")
    @PutMapping("/pwd/{id}")
    public Response updatePwd(@PathVariable("id") Long id,@Valid @RequestBody UpdatePwdForm updatePwdForm, @ApiIgnore @RequestAttribute("userId") String userId) {
        userService.updatePwd(id, updatePwdForm.getPwd(), new Long(userId));
        return new Response().setOK();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Response login(@RequestBody @Valid LoginRequest loginRequest) throws Exception {
        return new Response().setData(userService.login(loginRequest));
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public Response deleteUser(@PathVariable("id") Long id) {
        userService.deleteUser(id);
        return new Response().setOK();
    }


}
